package com.tarena.csmall.sso.service;

import cn.hutool.core.lang.Assert;
import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.admin.model.Admin;
import cn.tedu.mall.common.pojo.sso.authentication.CsmallAuthenticationInfo;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.common.utils.JwtTokenUtils;
import com.tarena.csmall.sso.mapper.AdminMapper;
import com.tarena.csmall.sso.pojo.dto.AdminLoginDTO;
import com.tarena.csmall.sso.utils.Asserts;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class AdminSSOService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /*@Autowired
    private RedisTemplate redisTemplate;*/
    /**
     * 判断username是否存在,不存在则抛出异常 username notfound
     * @param dto
     * @return
     */
    public String doLogin(AdminLoginDTO dto) {
        int countUsername=adminMapper.countByUsername(dto.getUsername());
        Asserts.isTrue(countUsername==0,new CoolSharkServiceException(ResponseCode.NOT_FOUND,"用户名不存在"));
        //判断异常,减少if else编写,默认的异常不是酷鲨的业务异常csmallservicexceptin 可以自定义封装一个
        Admin admin=adminMapper.findByUsername(dto.getUsername());
        //security 密码应该是加密过的
        Asserts.isTrue(!dto.getPassword().equals(admin.getPassword()),new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"密码不正确"));
        //读取权限
        List<String> authorities= adminMapper.findPermissionsByUsername(dto.getUsername());
        //没有权限,抛异常
        Asserts.isTrue(authorities==null||authorities.size()==0,new CoolSharkServiceException(ResponseCode.NOT_FOUND,"当前用户没有任何权限"));
        //登录验证结束,下面生成jwt CsmallUserInfo
        CsmallAuthenticationInfo csmallAuthenticationInfo=new CsmallAuthenticationInfo();
        csmallAuthenticationInfo.setId(admin.getId());
        csmallAuthenticationInfo.setUsername(dto.getUsername());
        csmallAuthenticationInfo.setUserType("ADMIN");
        csmallAuthenticationInfo.setAuthorities(authorities);
        String token = jwtTokenUtils.generateToken(csmallAuthenticationInfo);
        System.out.println("拿到登录token:"+token);
        return token;
    }

    public void logout(String token) {
        //定义一个黑名单key值
        String blackListKey="mall:sso:black:list:token:";
        SetOperations<String, String> operations =
            stringRedisTemplate.opsForSet();
        operations.add(blackListKey,token);
    }
}
